package com.idea.dsl.validator;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.idea.dsl.model.DslResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 业务规则DSL验证器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class BusinessRuleDslValidator implements DslValidator {
    
    private final ObjectMapper objectMapper;
    
    // 支持的操作符
    private static final List<String> SUPPORTED_OPERATORS = Arrays.asList(
        "not_empty", "empty", "equals", "not_equals", "contains", "not_contains",
        "in", "not_in", "greater_than", "less_than", "regex", "length_min", 
        "length_max", "date_format", "custom"
    );
    
    // 支持的动作类型
    private static final List<String> SUPPORTED_ACTION_TYPES = Arrays.asList(
        "错误", "警告", "信息", "error", "warning", "info"
    );
    
    @Override
    public DslResponse.ValidationResult validate(String dslContent, String dslType) {
        List<String> errors = new ArrayList<>();
        List<String> warnings = new ArrayList<>();
        boolean syntaxValid = true;
        boolean semanticValid = true;
        
        try {
            // JSON语法验证
            JsonNode rootNode = objectMapper.readTree(dslContent);
            log.debug("业务规则DSL语法验证通过");
            
            // 语义验证
            semanticValid = validateBusinessRuleSemantics(rootNode, errors, warnings);
            
        } catch (Exception e) {
            syntaxValid = false;
            errors.add("业务规则DSL语法错误: " + e.getMessage());
            log.warn("业务规则DSL语法验证失败: {}", e.getMessage());
        }
        
        boolean valid = syntaxValid && semanticValid && errors.isEmpty();
        
        return DslResponse.ValidationResult.builder()
                .valid(valid)
                .errors(errors)
                .warnings(warnings)
                .syntaxValid(syntaxValid)
                .semanticValid(semanticValid)
                .build();
    }
    
    private boolean validateBusinessRuleSemantics(JsonNode rootNode, List<String> errors, List<String> warnings) {
        boolean isValid = true;
        
        // 验证必填字段
        if (!rootNode.has("id") || rootNode.get("id").asText().trim().isEmpty()) {
            errors.add("缺少必填字段: id");
            isValid = false;
        }
        
        if (!rootNode.has("name") || rootNode.get("name").asText().trim().isEmpty()) {
            errors.add("缺少必填字段: name");
            isValid = false;
        }
        
        if (!rootNode.has("conditions")) {
            errors.add("缺少必填字段: conditions");
            isValid = false;
        } else {
            // 验证条件数组
            JsonNode conditions = rootNode.get("conditions");
            if (!conditions.isArray()) {
                errors.add("conditions字段必须是数组");
                isValid = false;
            } else if (conditions.size() == 0) {
                warnings.add("conditions数组为空");
            } else {
                // 验证每个条件
                for (int i = 0; i < conditions.size(); i++) {
                    JsonNode condition = conditions.get(i);
                    if (!validateCondition(condition, i, errors, warnings)) {
                        isValid = false;
                    }
                }
            }
        }
        
        if (!rootNode.has("action")) {
            errors.add("缺少必填字段: action");
            isValid = false;
        } else {
            // 验证动作
            if (!validateAction(rootNode.get("action"), errors, warnings)) {
                isValid = false;
            }
        }
        
        // 验证可选字段
        if (rootNode.has("priority")) {
            JsonNode priority = rootNode.get("priority");
            if (!priority.isNumber()) {
                errors.add("priority字段必须是数字");
                isValid = false;
            } else {
                int priorityValue = priority.asInt();
                if (priorityValue < 1 || priorityValue > 10) {
                    warnings.add("建议priority值在1-10之间");
                }
            }
        }
        
        if (rootNode.has("enabled")) {
            JsonNode enabled = rootNode.get("enabled");
            if (!enabled.isBoolean()) {
                errors.add("enabled字段必须是布尔值");
                isValid = false;
            }
        }
        
        return isValid;
    }
    
    private boolean validateCondition(JsonNode condition, int index, List<String> errors, List<String> warnings) {
        boolean isValid = true;
        String prefix = "conditions[" + index + "]";
        
        // 验证field字段
        if (!condition.has("field") || condition.get("field").asText().trim().isEmpty()) {
            errors.add(prefix + "缺少必填字段: field");
            isValid = false;
        }
        
        // 验证operator字段
        if (!condition.has("operator")) {
            errors.add(prefix + "缺少必填字段: operator");
            isValid = false;
        } else {
            String operator = condition.get("operator").asText();
            if (!SUPPORTED_OPERATORS.contains(operator)) {
                errors.add(prefix + "不支持的操作符: " + operator);
                isValid = false;
            }
        }
        
        // 验证logicalOperator字段
        if (condition.has("logicalOperator")) {
            String logicalOperator = condition.get("logicalOperator").asText();
            if (!"and".equals(logicalOperator) && !"or".equals(logicalOperator)) {
                errors.add(prefix + "logicalOperator只支持'and'或'or'");
                isValid = false;
            }
        }
        
        return isValid;
    }
    
    private boolean validateAction(JsonNode action, List<String> errors, List<String> warnings) {
        boolean isValid = true;
        
        // 验证type字段
        if (!action.has("type")) {
            errors.add("action缺少必填字段: type");
            isValid = false;
        } else {
            String type = action.get("type").asText();
            if (!SUPPORTED_ACTION_TYPES.contains(type)) {
                warnings.add("action.type建议使用: " + String.join(", ", SUPPORTED_ACTION_TYPES));
            }
        }
        
        // 验证message字段
        if (!action.has("message") || action.get("message").asText().trim().isEmpty()) {
            errors.add("action缺少必填字段: message");
            isValid = false;
        }
        
        return isValid;
    }
    
    @Override
    public String getSupportedDslType() {
        return "business-rule";
    }
    
    @Override
    public boolean supports(String dslType) {
        return "business-rule".equalsIgnoreCase(dslType) || 
               "rule".equalsIgnoreCase(dslType) ||
               "business_rule".equalsIgnoreCase(dslType);
    }
}
